/*
 * Transport.c
 *
 *  Created on: 2012-11-30
 *      Author: silvtar
 */

/*
 * Transport.cpp
 *
 *  Created on: 2012-11-30
 *      Author: silvtar
 */
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "fcntl.h"

const int BUFFSIZE = 4096;
const int COPYMODE = 0644;
int copy_file_sys(const char* source, const char* aim)
{
	pid_t child_pid;
	int exestate;
	child_pid = fork();
	if((child_pid = fork()) == 0)
	{
		char argv[0][10];
		sprintf(argv[0],"cp");
		sprintf(argv[1],"-p");
		strcpy(argv[2], source);
		strcpy(argv[3], aim);
		execvp(argv[0],(char**)argv);
		perror("execvp failed");
		exit(0);
	}
	else
		waitpid(child_pid, &exestate, 0);

	return 0;
}
int copy_file(const char* source, const char* aim) {
	int in_fd = -1;         //源文件标识
	int out_fd = -1;        //目标文件标识符
	int n_chars = 0;        //读取到的字节数
	char buf[BUFFSIZE];		//缓冲区

	//打开源文件
	if ((in_fd = open(source, O_RDONLY)) == -1) {
		fprintf(stderr, "can't open %s\n", source);
		return -1;
	}

	//打开目标文件
	if ((out_fd = creat(aim, COPYMODE)) == -1) {
		fprintf(stderr, "can't create %s\n", aim);
		return -2;
	}

	//开始循环写入
	while ((n_chars = read(in_fd, buf, BUFFSIZE)) > 0)

		if (write(out_fd, buf, n_chars) != n_chars) {
			fprintf(stderr, "write error to %s\n", aim);
			return -3;
		}

	//写入时间戳


	//检测
	if (n_chars == -1) {
		fprintf(stderr, "Read error from %s\n", source);
		return -4;
	}

	if (close(in_fd) == -1 || close(out_fd) == -1) {
		fprintf(stderr, "Error closing files\n");
		return -5;
	}

	return 0;
}

